﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kingdee.WeksErp.DAL;
using Kingdee.WeksErp.Models.Orders;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using Kingdee.WeksErp.Models.Orders.Dto;
using Kingdee.WeksErp.Models.Suppliers.Dto;

namespace Kingdee.WeksErp.Controllers
{
    public class OrderController : BaseController
    {
        private WeksErpContext db = new WeksErpContext();
        #region 威尔康赛功能
        #region Views
        /// <summary>
        /// 淘宝订单-已审核
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
            return View();
        }

        /// <summary>
        /// 物流比价
        /// </summary>
        /// <returns></returns>
        public ActionResult CompareList()
        {
            return View();
        }

        public ActionResult Manager()
        {
            return View();
        }

        /// <summary>
        /// 数据同步与备注解析
        /// </summary>
        /// <returns></returns>
        public ActionResult SyncOrders()
        {
            try
            {
                var syncs = db.Database.SqlQuery<SyncResult>("dbo.SyncProc").ToList();
                return Json(new
                {
                    success = true,
                    msg = ""
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                return Json(new
                {
                    success = false,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }


        [HttpPost]
        public ActionResult Dispath(string orders, string suppliers)
        {
            try
            {
                var count = db.Database.ExecuteSqlCommand("dbo.OrderDispathProc @OrderId ,@SupplierId", new SqlParameter("@OrderId", orders.Replace('[', ' ').Replace(']', ' ').Trim()), new SqlParameter("@SupplierId", suppliers.Replace('[', ' ').Replace(']', ' ').Trim()));
                return Json(new
                {
                    success = true,
                    msg = count
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult OrderBjDetail(int orderid)
        {
            var order = db.TbOrders.FirstOrDefault(t => t.FOrderId == orderid);
            return View(order);
        }
        #endregion
        #region Datas

        public ActionResult ManagerData()
        {
            int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);
            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int status = -1;
            var tmp = db.TbOrders.Where(t => true);
            if (int.TryParse(Request["status"] ?? "", out status))
            {
                try
                {
                    if (status != -1)
                    {
                        tmp = tmp.Where(t => t.Status == (OrderStatus)status);
                    }
                }
                catch (Exception)
                {
                    //ignore
                }
            }
            if (!string.IsNullOrEmpty(Request["key"]) && !string.IsNullOrEmpty(Request["value"]))
            {
                string value = Request["value"];
                switch (Request["key"])
                {
                    case "FOrderNo":
                        tmp = tmp.Where(t => t.FOrderNo.Contains(value));
                        break;
                    case "FShrName":
                        tmp = tmp.Where(t => t.FShrName.Contains(value));
                        break;
                }
            }
            var total = tmp.Count();
            //分页的处理
            var rows = tmp.Select(t => new
            {
                t.FOrderId,
                t.FOrderNo,
                t.FStoreName,
                t.FVipName,
                t.FShrName,
                t.FShrTel,
                t.FDeliveryDistrict,
                t.FAddress,
                t.FDt,
                t.Status,
                t.FIndex,
                t.FItemName,
                t.FGgModel,
                t.FQty,
                t.FWeight,
                t.FVolume,
                t.FBjPrice,
                t.TranspPrice1,
                t.TranspPrice2,
                t.FTranspBillNo
            }).OrderBy(t => t.FOrderId).ThenBy(t => t.FIndex).Skip(pageSize * (pageIndex - 1)).Take(pageSize).AsQueryable();
            var list = new
            {
                total,
                rows
            };

            return Json(list, JsonRequestBehavior.AllowGet);
        }
        public ActionResult ListData()
        {
            var list = db.TbOrders.Where(t => t.Status == OrderStatus.Checked).OrderBy(t => t.FOrderId).ThenBy(t => t.FIndex).ToList();
            //int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);
            //int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            //var list = db.TbOrders.Where(t => t.Status == OrderStatus.Checked).OrderBy(t => t.FOrderId).ThenBy(t => t.FIndex).Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
            //var strSql = new StringBuilder();

            //strSql.AppendLine("SELECT DISTINCT");
            //strSql.AppendLine("        FOrderId ,");
            //strSql.AppendLine("        FOrderNo ,");
            //strSql.AppendLine("        FStoreName ,");
            //strSql.AppendLine("        FVipName ,");
            //strSql.AppendLine("        FShrName ,");
            //strSql.AppendLine("        FShrTel ,");
            //strSql.AppendLine("        FDeliveryDistrict ,");
            //strSql.AppendLine("        FDt ,");
            //strSql.AppendLine("        FAddress");
            //strSql.AppendLine("FROM    dbo.TbOrders");
            //strSql.AppendLine("WHERE   Status = 0");
            //var list = db.Database.SqlQuery<TbOrderDto>(strSql.ToString()).ToList();
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 物流比价列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult CompareData()
        {
            var strSql = new StringBuilder();
            strSql.AppendLine("SELECT distinct");
            strSql.AppendLine("        a.FOrderId ,");
            strSql.AppendLine("        a.FIndex ,");
            strSql.AppendLine("        a.FOrderNo ,");
            strSql.AppendLine("        a.FStoreName ,");
            strSql.AppendLine("        a.FVipName ,");
            strSql.AppendLine("        a.FShrName ,");
            strSql.AppendLine("        a.FShrTel ,");
            strSql.AppendLine("        a.FDeliveryDistrict ,");
            strSql.AppendLine("        a.FDt ,");
            strSql.AppendLine("        a.FAddress,");
            strSql.AppendLine("        a.FItemName ,");
            strSql.AppendLine("        a.FGgModel ,");
            strSql.AppendLine("        a.FQty ,");
            strSql.AppendLine("        a.FWeight ,");
            strSql.AppendLine("        a.FVolume ,");
            strSql.AppendLine("        a.FBjPrice ,");
            strSql.AppendLine("  case when a.TranspPrice1>0 then a.TranspPrice1 else a.TranspPrice2 end as FCost,");
            strSql.AppendLine("        a.TranspPrice1 ,");
            strSql.AppendLine("        a.TranspPrice2,");
            strSql.AppendLine("        b.FName as SupplierName");
            strSql.AppendLine("FROM    dbo.TbOrders a");
            strSql.AppendLine("        INNER JOIN dbo.IC_Logistics b ON a.FSupplierID = b.FItemId");
            //strSql.AppendLine("  where a.FSupplierID=@FSupplierID");
            strSql.AppendLine("     where a.Status=1");
            var list = db.Database.SqlQuery<TbOrderCompareDto>(strSql.ToString()).ToList();
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 报价确认
        /// </summary>
        /// <param name="orders"></param>
        /// <returns></returns>
        public ActionResult ConfirmSupplier(string orders)
        {
            try
            {
                var count = db.Database.ExecuteSqlCommand("dbo.OrderConfirmProc @OrderId", new SqlParameter("@OrderId", orders.Replace('[', ' ').Replace(']', ' ').Trim()));
                return Json(new
                {
                    success = true,
                    msg = count
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                return Json(new
                {
                    success = false,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 报价确认
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="supplierid"></param>
        /// <returns></returns>
        public ActionResult ConfirmBj(int orderid, int supplierid)
        {
            try
            {
                //var count = db.Database.ExecuteSqlCommand(
                //        " update tborders set FSupplierId=@FSupplierId, Status=2 where Status=1 and FOrderId=@FOrderId",
                //        new SqlParameter("@FSupplierId", supplierid), new SqlParameter("@FOrderId", orderid));
                var count = db.Database.ExecuteSqlCommand(" dbo.OrderConfirmBjProc @FOrderId,@FSupplierId",
                        new SqlParameter("@FSupplierId", supplierid), new SqlParameter("@FOrderId", orderid));
                return Json(new { success = count > 0, msg = "" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                return Json(new { success = false, msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult BjDetail(int orderid)
        {
            var strSql = new StringBuilder();
            strSql.AppendLine("SELECT a.FOrderNo,a.FIndex, e.FName AS SupplierName ,");
            strSql.AppendLine("        a.FItemName ,");
            strSql.AppendLine("        a.FGgModel ,");
            strSql.AppendLine("        a.FQty ,");
            strSql.AppendLine("        a.FWeight ,");
            strSql.AppendLine("        a.FVolume ,");
            strSql.AppendLine("        a.FBjPrice ,");
            strSql.AppendLine("        a.FDt ,");
            strSql.AppendLine("       convert(varchar(50),c.TranspPrice1) as TranspPrice1,");
            strSql.AppendLine("        convert(varchar(50),c.TranspPrice2) as TranspPrice2 ,");
            strSql.AppendLine("       CONVERT(VARCHAR(50), c.TranspPrice1 * ISNULL(d.Coefficient, 1)) AS FCost1 ,");
            strSql.AppendLine("     CONVERT(VARCHAR(50), c.TranspPrice2 * ISNULL(d.Coefficient, 1)) AS FCost2 ,");
            strSql.AppendLine("     CONVERT(VARCHAR(50), ISNULL(d.Coefficient, 1)) AS Fxs");
            strSql.AppendLine("FROM    dbo.TbOrders a");
            //strSql.AppendLine("        INNER JOIN dbo.TbOrderDispath b ON a.FOrderId = b.FOrderID");
            strSql.AppendLine("        INNER JOIN dbo.TbOrderSupplier c ON c.FOrderId = a.FOrderID and a.FIndex=c.FIndex");
            //strSql.AppendLine("                                            AND c.FSupplierId = b.FSupplierID");
            strSql.AppendLine("        LEFT JOIN dbo.TranspSupplierCofs d ON c.FSupplierId = d.FItemId");
            strSql.AppendLine("                                              AND a.FDeliveryDistrict = d.FCountryId");
            strSql.AppendLine("        LEFT JOIN dbo.IC_Logistics e ON  c.FSupplierId = e.FItemId");
            strSql.AppendLine("WHERE  a.FOrderId=@FOrderId and a.FIndex=1");
            strSql.AppendLine(" order by e.FName,a.FIndex");
            var list = db.Database.SqlQuery<SupplierBj>(strSql.ToString(), new SqlParameter("@FOrderId", orderid));
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SupplierDispathed(int orderid)
        {
            var list = db.Database.SqlQuery<TranspSupplierDto>(" SELECT distinct  b.FItemID,b.FName FROM dbo.TbOrderDispath  a INNER JOIN  dbo.IC_Logistics b ON a.FSupplierID=b.FItemID WHERE a.FOrderID=@FOrderID", new SqlParameter("@FOrderId", orderid)).ToList();
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        #endregion
        #endregion

        #region 物流公司功能
        /// <summary>
        /// 待报价
        /// </summary>
        /// <returns></returns>
        public ActionResult Quote()
        {
            return View();
        }

        public ActionResult QuoteData()
        {
            var list = GetBjData();
            return Json(list, JsonRequestBehavior.AllowGet);
        }



        public ActionResult Bj()
        {
            var list = GetBjData();
            return View(list);
        }

        private List<TbOrder> GetBjData()
        {
            var strSql = new StringBuilder();
            strSql.AppendLine("SELECT  a.ID ,");
            strSql.AppendLine("        a.FOrderId ,");
            strSql.AppendLine("        a.FIndex ,");
            strSql.AppendLine("        a.FWeightTotal ,");
            strSql.AppendLine("        a.FOrderNo ,");
            strSql.AppendLine("        a.FStoreName ,");
            strSql.AppendLine("        a.FVipName ,");
            strSql.AppendLine("        a.FShrName ,");
            strSql.AppendLine("        a.FShrTel ,");
            strSql.AppendLine("        a.FDeliveryProvince ,");
            strSql.AppendLine("        a.FDeliveryCity ,");
            strSql.AppendLine("        a.FDeliveryDistrict ,");
            strSql.AppendLine("        a.FAddress ,");
            strSql.AppendLine("        a.FItemName ,");
            strSql.AppendLine("        a.FGgModel ,");
            strSql.AppendLine("        a.FQty ,");
            strSql.AppendLine("        a.FWeight ,");
            strSql.AppendLine("        a.FVolume ,");
            strSql.AppendLine("        a.FBjPrice ,");
            strSql.AppendLine("        a.FDt ,");
            strSql.AppendLine("        b.FSupplierID ,");
            strSql.AppendLine("        0.0 as TranspPrice1 ,");
            strSql.AppendLine("        0.0 as TranspPrice2,");
            strSql.AppendLine("        a.CreationTime,");
            strSql.AppendLine("        a.FTranspBillNo,");
            strSql.AppendLine("        a.Status");
            strSql.AppendLine("FROM    dbo.TbOrders a");
            strSql.AppendLine("        INNER JOIN (select distinct  FOrderID,FSupplierID from TbOrderDispath) b ON a.FOrderId = b.FOrderID");
            strSql.AppendLine("        LEFT JOIN dbo.TbOrderSupplier c ON c.FOrderId = b.FOrderID");
            strSql.AppendLine("                                           AND c.FSupplierId = b.FSupplierID ");
            strSql.AppendLine("WHERE   b.FSupplierID = @FSupplierID and a.Status=1");
            strSql.AppendLine("        AND c.ID IS NULL");
            strSql.AppendLine("        order by a.FDeliveryProvince,a.FDeliveryCity,a.FDeliveryDistrict,a.FOrderId,a.FIndex");
            return db.TbOrders.SqlQuery(strSql.ToString(), new SqlParameter("@FSupplierID", CurrentUserInfo.SupplierId)).ToList();
        }

        /// <summary>
        /// 供应商报价
        /// </summary>
        /// <param name="orders"></param>
        /// <returns></returns>
        public ActionResult SupplierBj(List<TbOrder> orders)
        {
            try
            {

                foreach (var order in orders)
                {
                    db.Database.ExecuteSqlCommand("dbo.OrderBjProc @FOrderId,@FIndex,@FSupplierId,@TranspPrice1,@TranspPrice2", new SqlParameter("@FOrderId", order.FOrderId), new SqlParameter("@FIndex", order.FIndex), new SqlParameter("@FSupplierId", order.FSupplierId), new SqlParameter("@TranspPrice1", order.TranspPrice1), new SqlParameter("@TranspPrice2", order.TranspPrice2));
                }
                return Json(new
                {
                    success = true,
                    msg = ""
                }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }


        public ActionResult BjSubmit(List<BjInput> orders)
        {
            try
            {
                foreach (var order in orders)
                {
                    db.Database.ExecuteSqlCommand("dbo.OrderBjProc @FOrderId,@FIndex,@FSupplierId,@TranspPrice1,@TranspPrice2", new SqlParameter("@FOrderId", order.FOrderId), new SqlParameter("@FIndex", order.FIndex), new SqlParameter("@FSupplierId", CurrentUserInfo.SupplierId), new SqlParameter("@TranspPrice1", order.Price1), new SqlParameter("@TranspPrice2", order.Price2));
                }
                return Json(new
                {
                    success = true,
                    msg = ""
                }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message
                }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 历史报价
        /// </summary>
        /// <returns></returns>
        public ActionResult QuoteHistory()
        {
            return View();
        }

        public ActionResult QuoteHistoryData()
        {
            var strSql = new StringBuilder();
            strSql.AppendLine("SELECT  a.ID ,");
            strSql.AppendLine("        a.FOrderId ,");
            strSql.AppendLine("        a.FIndex ,");
            strSql.AppendLine("        a.FWeightTotal ,");
            strSql.AppendLine("        a.FOrderNo ,");
            strSql.AppendLine("        a.FStoreName ,");
            strSql.AppendLine("        a.FVipName ,");
            strSql.AppendLine("        a.FShrName ,");
            strSql.AppendLine("        a.FShrTel ,");
            strSql.AppendLine("        a.FDeliveryProvince ,");
            strSql.AppendLine("        a.FDeliveryCity ,");
            strSql.AppendLine("        a.FDeliveryDistrict ,");
            strSql.AppendLine("        a.FAddress ,");
            strSql.AppendLine("        a.FItemName ,");
            strSql.AppendLine("        a.FGgModel ,");
            strSql.AppendLine("        a.FQty ,");
            strSql.AppendLine("        a.FWeight ,");
            strSql.AppendLine("        a.FVolume ,");
            strSql.AppendLine("        a.FBjPrice ,");
            strSql.AppendLine("        a.FDt ,");
            strSql.AppendLine("        c.FSupplierID ,");
            strSql.AppendLine("        c.TranspPrice1 ,");
            strSql.AppendLine("        c.TranspPrice2,");
            strSql.AppendLine("        a.CreationTime,");
            strSql.AppendLine(" a.FTranspBillNo,");
            strSql.AppendLine("        a.Status");
            strSql.AppendLine("FROM    dbo.TbOrders a");

            strSql.AppendLine("        inner  JOIN dbo.TbOrderSupplier c ON c.FOrderId = a.FOrderID");
            //strSql.AppendLine("                                           AND c.FIndex = a.FIndex");
            strSql.AppendLine("WHERE   c.FSupplierID = @FSupplierID");
            strSql.AppendLine(" order by a.Status desc, a.FOrderNo desc, a.FIndex");
            var list = db.TbOrders.SqlQuery(strSql.ToString(), new SqlParameter("@FSupplierID", CurrentUserInfo.SupplierId)).ToList();
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 我的货单
        /// </summary>
        /// <returns></returns>
        public ActionResult Deal()
        {
            return View();
        }

        public ActionResult DealData()
        {
            var strSql = new StringBuilder();
            strSql.AppendLine("SELECT  a.ID ,");
            strSql.AppendLine("        a.FOrderId ,");
            strSql.AppendLine("        a.FIndex ,");
            strSql.AppendLine("        a.FOrderNo ,");
            strSql.AppendLine("        a.FStoreName ,");
            strSql.AppendLine("        a.FVipName ,");
            strSql.AppendLine("        a.FShrName ,");
            strSql.AppendLine("        a.FShrTel ,");
            strSql.AppendLine("        a.FDeliveryProvince ,");
            strSql.AppendLine("        a.FDeliveryCity ,");
            strSql.AppendLine("        a.FDeliveryDistrict ,");
            strSql.AppendLine("        a.FAddress ,");
            strSql.AppendLine("        a.FItemName ,");
            strSql.AppendLine("        a.FGgModel ,");
            strSql.AppendLine("        a.FQty ,");
            strSql.AppendLine("        a.FWeight ,");
            strSql.AppendLine("        a.FVolume ,");
            strSql.AppendLine("        a.FBjPrice ,");
            strSql.AppendLine("        a.FDt ,");
            strSql.AppendLine("        a.FSupplierID ,");
            strSql.AppendLine("        a.TranspPrice1 ,");
            strSql.AppendLine("        a.TranspPrice2,");
            strSql.AppendLine("        a.CreationTime,");
            strSql.AppendLine("        '' as SupplierName,");
            strSql.AppendLine("        FTranspBillNo,");
            strSql.AppendLine("        a.Status");
            strSql.AppendLine("FROM    dbo.TbOrders a");
            strSql.AppendLine("WHERE   FSupplierID = @FSupplierID and Status>=2  order by a.Status ");
            var list = db.Database.SqlQuery<TbOrderTransp>(strSql.ToString(), new SqlParameter("@FSupplierID", CurrentUserInfo.SupplierId)).ToList();
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SubmitTranspNo(string tspNo, int orderid)
        {
            try
            {
                if (tspNo.Trim().Length == 0)
                {
                    return Json(new { success = false, msg = "请输入物流单号" }, JsonRequestBehavior.AllowGet);
                }
                int count = db.Database.ExecuteSqlCommand("dbo.SubmitTranspNoProc @FOrderId,@FTranspNo", new SqlParameter("@FOrderId", orderid), new SqlParameter("@FTranspNo", tspNo));
                return Json(new { success = count > 0, msg = "操作失败！" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                return Json(new { success = false, msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}